package com.zbb.online_exam.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbb.online_exam.dto.TableDto;
import com.zbb.online_exam.dto.UserDto;
import com.zbb.online_exam.entity.Question;
import com.zbb.online_exam.exception.ExamException;
import com.zbb.online_exam.mapper.QuestionMapper;
import com.zbb.online_exam.service.QuestionService;
import com.zbb.online_exam.service.UserService;
import com.zbb.online_exam.utils.ExamUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;

import static com.zbb.online_exam.constant.BusinessConstant.ADMIN_PERMIT_VALUE;


/**
 * @author zbbstart
 * @date 2021/2/12 - 13:04
 */
@Service
@Slf4j
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private ExamUtils examUtils;
    @Autowired
    private UserService userService;

    @Override
    public TableDto getAllQuestionsByPage(Integer pageNo, Integer size) {
        //分页查询 pageNo 页码，size 页面的条数
        Page<Question> page = new Page<>(pageNo, size);
        //获取分页结果
        Page<Question> questionPage = questionMapper.selectPage(page, new QueryWrapper<Question>());
        //获取所有的题目
        List<Question> questions = questionPage.getRecords();
        //判空
        if (CollectionUtils.isEmpty(questions)) {
            return examUtils.setTableDto();
        }
        //获取所有的题目数量
        long total = questionPage.getTotal();
        return examUtils.setTableDto(total, questions);
    }

    /**
     * 新增题目
     */
    @Override
    public void addQuestion(Question question, String token) {
        //获取授权的用户信息
        UserDto userDto = userService.getUserInfoByToken(token);
        question.setTeacherNo(Integer.parseInt(userDto.getUserId()));
        questionMapper.insert(question);
    }

    @Override
    public void updateQuestion(Question question) {
        Question oldQuestion = getQuestionByQuestionId(question.getQuestionId());
        //获取老师编号
        Integer teacherNo = question.getTeacherNo();

        //是否是管理员
        if (teacherNo.equals(ADMIN_PERMIT_VALUE)) {
            // examUtils.isSame判断是否改变了题目，否则抛出异常
            examUtils.isSame(oldQuestion, question);
            //打印要修改的题目信息
            log.info(question.toString());
            questionMapper.updateById(question);
        } else {
            List<Question> questionList = getQuestionsByTeacherNo(teacherNo);
            // anyMatch：判断的条件里，任意一个元素成功，返回true
            boolean flag = questionList
                    .stream()
                    .map(Question::getQuestionId)
                    .anyMatch(q -> q.equals(question.getQuestionId()));
            if (flag) {
                examUtils.isSame(oldQuestion, question);
                questionMapper.updateById(question);
            } else {
                throw new ExamException("权限不足，请联系管理员修改!");
            }
        }

    }

    @Override
    public Question getQuestionByQuestionId(Integer questionId) {
        return questionMapper.selectById(questionId);
    }

    @Override
    public List<Question> getQuestionsByTeacherNo(Integer teacherNo) {
        List<Question> questionList = questionMapper.selectList(new QueryWrapper<Question>().eq("teacherNo", teacherNo));
        if (CollectionUtils.isEmpty(questionList)) {
            throw new ExamException("您当前还没有创建题目...");
        }
        return questionList;
    }

    @Override
    public void deleteQuestions(List<Integer> questionIds, String token) {
        UserDto userDto = userService.getUserInfoByToken(token);
        Integer userId = Integer.parseInt(userDto.getUserId());
        if (userId.equals(ADMIN_PERMIT_VALUE)) {
            questionMapper.deleteBatchIds(questionIds);
        } else {
            List<Question> questionList = getQuestionsByTeacherNo(userId);
            // intersection：apache工具包，判断两个集合是否有交集
            Collection collection = CollectionUtils.intersection(questionIds, questionList);
            if (CollectionUtils.isNotEmpty(collection)) {
                questionMapper.deleteBatchIds(questionIds);
            } else {
                throw new ExamException("权限不足，请联系管理员修改!");
            }
        }
    }

    @Override
    public TableDto likeSearchQuestions(String keyWord, Integer pageNo, Integer size) {
        //分页查询 pageNo 页码，size 页面的条数
        Page<Question> page = new Page<>(pageNo, size);
        //获取分页结果
        Page<Question> questionPage = questionMapper.selectPage(page,
                new QueryWrapper<Question>().like("questionContent", keyWord).or()
                        .like("answerA", keyWord).or().like("answerB", keyWord)
                        .or().like("answerC", keyWord).or().like("answerD", keyWord));
        //获取所有的题目
        List<Question> questions = questionPage.getRecords();
        //判空
        if (CollectionUtils.isEmpty(questions)) {
            throw new ExamException("查询不到...");
        }
        //获取所有的题目数量
        long total = questionPage.getTotal();
        return examUtils.setTableDto(total, questions);
    }
}
